package js.web.center.utils;
/**
 * 访问异步控制
 * @author dowell
 *
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.ThreadPoolExecutor;

import js.web.center.core.config.JsWebConfig;

public class JsWebSyncCtrlUtils {
	public static ThreadPoolExecutor executor=null;
	/**
	 * 加锁对象
	 */
	private static HashMap<String, Object> hashMap=new HashMap<>();
	/**
	 * session活跃时间
	 */
	private static HashMap<String, Long> updateTime=new HashMap<>();
	/**
	 * session保存对象
	 */
	private static HashMap<String, HashMap<String,Object>> map=new HashMap<>();
	/**
	 * 添加sesionId
	 * @param sessionId
	 */
	public synchronized static void addSession(String sessionId){
		hashMap.put(sessionId, new Object());
		map.put(sessionId, new HashMap<String,Object>(JsWebConfig.maxSessionNum));
		updateTime.put(sessionId, System.currentTimeMillis());
	}
	/**
	 * 判断sessionId是否存在
	 * @param sessionId
	 * @return
	 */
	public static boolean hadSessionId(String sessionId){
		return hashMap.containsKey(sessionId);
	}
	/**
	 * 获取加锁对象
	 * @param sessionId
	 * @return
	 */
	public static Object getSessionObject(String sessionId){
		if(hashMap.containsKey(sessionId)){
			updateTime.put(sessionId, System.currentTimeMillis());
			return hashMap.get(sessionId);
		}
		return null;
	}
	/**
	 * 更新活跃时间
	 * @param sessionId
	 */
	public synchronized static void upateActiveTime(String sessionId){
		updateTime.put(sessionId, System.currentTimeMillis());
	}
	/**
	 * 删除sessionId
	 * @param sessionId
	 */
	public synchronized static void removeSessionId(String sessionId){
		hashMap.remove(sessionId);
		updateTime.remove(sessionId);
		map.remove(sessionId);
	}
	/**
	 * 获取session保存数据
	 * @param sessionId
	 * @return
	 */
	public static HashMap<String, Object> getSessionMap(String sessionId){
		return map.get(sessionId);
	}
	/**
	 * 返回所有session计时器
	 * @return
	 */
	public synchronized static ArrayList<Entry<String, Long>> getAllSessionIds(){
		ArrayList<Entry<String, Long>> list=new ArrayList<>();
		Iterator<Entry<String, Long>> iterator = updateTime.entrySet().iterator();
		while(iterator.hasNext()){
			Entry<String, Long> next = iterator.next();
			list.add(next);
		}
		return list;
	}
}